import React, { createContext } from "react";
// redux
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { setMqttRcvMsg, setMqttConnectState } from "../redux/actions";
import { openNotification } from "./notice";
import { message } from "antd";
import PahoMQTT from "../library/js/paho-mqtt";

// 1. 使用 createContext 创建上下文
export const MqttContext = createContext({});

// 2. 创建 Provider
class provider extends React.Component {
  constructor(props) {
    super(props);
    let cleanSession = false;
    let useSSL = false;
    // let hostname = "192.168.30.13";
    // let hostname = "192.168.20.250";
    let hostname = "47.99.160.114";
    let port = 8083;
    // let port = 1883;

    let clientId = Math.random().toString().slice(2); //实际为用户id
    /* eslint-disable no-undef */
    this.mqttClient = new PahoMQTT.Client(hostname, port, clientId);
    this.mqttoptions = {
      invocationContext: {
        host: hostname,
        port: port,
        clientId: clientId,
      },
      timeout: 5,
      cleanSession: cleanSession,
      useSSL: useSSL,
      userName: "admin",
      password: "admin",
      onSuccess: this.mqttConnectOk,
      onFailure: this.mqttConnectFail,
    };
    this.mqttoptionsback = Object.assign({}, this.mqttoptions);
    this.timer = {};
  }
  //连接失败回调函数
  mqttConnectFail = (e) => {
    console.log("MQTT连接失败,失败原因是", e);
  };
  mqttConnectOk = () => {
    console.log("WebSocket mqtt 连接成功!");
    //停止定时器

    clearTimeout(this.timer);

    //设置链接成功标志
    this.props.setMqttConnectState(true);

    console.log("开始订阅主应用默认主题");
    this.mqttClient.subscribe("out", { qos: 1 });
    this.mqttClient.subscribe("newapp", { qos: 1 }); //新应用发布主题
    console.log("订阅完成");
  };

  //收到消息回调函数
  messageArrived = (msg) => {
    let data = `MQTT 收到topic 为 ${msg.destinationName} 的消息，具体内容为: ${msg.payloadString}, 消息服务等级为 ${msg.qos}：`;
    console.log(data);
    //根据主题来进行处理
    if (msg.destinationName == "out") {
      message.info(msg.payloadString);
    } else if (msg.destinationName == "newapp") {
      console.log("new app");
      try {
        let data = JSON.parse(msg.payloadString);
        openNotification({
          msg: data.msg,
          desc: data.desc,
        });
      } catch (error) {
        console.log("处理消息出错，error is：", error);
        return;
      }
    } else if (msg.destinationName.startsWith("m2m")) {
      console.log("聊天数据");
      //聊天数据 后期聊天数据要从历史记录中get
      this.props.setMqttRcvMsg({
        topic: msg.destinationName,
        payload: msg.payloadString,
        qos: msg.qos,
      });
    }
  };
  connectLost = (response) => {
    console.log("MQTT 连接断开");
    console.log("MQTT 开始重连");
    this.reconnect();
  };
  reconnect = () => {
    this.timer = setTimeout(() => {
      this.mqttoptions = Object.assign({}, this.mqttoptionsback);
      this.mqttClient.connect(this.mqttoptions);
      this.reconnect();
    }, 3000); //注意，这里必须是三秒重连，否则会有报错情况，预计报错原因是因为在链接失败没有返回时又进行了重连
  };

  componentDidMount() {
    // console.log("this.mqttClient", this.mqttClient);
    // console.log("this.messageArrived", this.messageArrived);

    //设置mqtt消息回调函数
    this.mqttClient.onMessageArrived = this.messageArrived;
    this.mqttClient.onConnectionLost = this.connectLost;
    console.log("开始进行mqtt链接");
    this.mqttClient.connect(this.mqttoptions);
  }

  render() {
    // 2-2. 通过 Provider 组件的 value 将 state 提供出去
    return (
      <MqttContext.Provider value={this.mqttClient}>
        {this.props.children}
      </MqttContext.Provider>
    );
  }
}

//获取状态
const mapStateToProps = (state) => {
  return {
    state: state,
  };
};
//获取方法
const mapDispatchToProps = (dispath) => {
  return bindActionCreators(
    {
      setMqttRcvMsg,
      setMqttConnectState,
    },
    dispath
  );
};

export const MqttProvider = connect(
  mapStateToProps,
  mapDispatchToProps
)(provider);

// // 3. 创建 Consumer
// export const ToggleConsumer = ToggleContext.Consumer
